<template>
  <Page>
    <!-- 测试 Axios 请求 -->
    <div style="margin-top: 20px">
      <el-button ref="debounceBtn" @click="testDebounceRequests">测试防抖功能</el-button>
      <el-button ref="throttleBtn" @click="testThrottleRequests">测试节流功能</el-button>
      <el-button ref="cancelBtn" @click="testCancelRequest">测试取消请求功能</el-button>
    </div>

    <!-- 测试结果 -->
    <div style="margin-top: 20px">
      <h3>测试结果</h3>
      <pre>{{ testResults }}</pre>
    </div>
  </Page>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue'
import Page from '@/components/page/index'

// 获取当前实例
const { proxy } = getCurrentInstance()

// 定义 Refs
const debounceBtn = ref(null)
const throttleBtn = ref(null)
const cancelBtn = ref(null)

// 测试结果日志
const testResults = ref('')

/**
 * 格式化日志输出
 */
function log(message) {
  testResults.value += `${message}\n`
}

/**
 * 测试防抖功能
 */
function testDebounceRequests() {
  if (debounceBtn.value) {
    proxy.$loading.show(debounceBtn.value)
  }

  for (let i = 0; i < 5; i++) {
    proxy.$axios
      .get('/todos/1', { id: i }, { throttle: false })
      .then(response => log(`响应 ${i}: ${JSON.stringify(response.data)}`))
      .catch(error => log(`防抖 ${i}: ${error.message}`))
      .finally(() => {
        if (debounceBtn.value && i === 4) {
          proxy.$loading.hide(debounceBtn.value)
        }
      })
  }
}

/**
 * 测试节流功能
 */
function testThrottleRequests() {
  if (throttleBtn.value) {
    proxy.$loading.show(throttleBtn.value)
  }

  for (let i = 0; i < 5; i++) {
    proxy.$axios
      .get('/todos/1', { id: 1 }, { debounce: false })
      .then(response => log(`响应 ${i}: ${JSON.stringify(response.data)}`))
      .catch(error => log(`节流 ${i}: ${error.message}`))
      .finally(() => {
        if (throttleBtn.value && i === 4) {
          proxy.$loading.hide(throttleBtn.value)
        }
      })
  }
}

/**
 * 测试取消请求功能
 */
async function testCancelRequest() {
  if (cancelBtn.value) {
    proxy.$loading.show(cancelBtn.value)
  }

  try {
    const response = await proxy.$axios.post('/long-running', { id: 1 }, { debounce: true, isNeedNew: true })
    log(`响应 1: ${JSON.stringify(response.data)}`)
  } catch (error) {
    log(`请求1已取消: ${error.message}`)
  } finally {
    if (cancelBtn.value) {
      proxy.$loading.hide(cancelBtn.value)
    }
  }

  // 模拟 1000ms 后发起第二个请求
  setTimeout(async () => {
    if (cancelBtn.value) {
      proxy.$loading.show(cancelBtn.value)
    }

    try {
      const response = await proxy.$axios.post('/long-running', { id: 12 }, { debounce: true, isNeedNew: true })
      log(`响应 2: ${JSON.stringify(response.data)}`)
    } catch (error) {
      log(`请求2已取消: ${error.message}`)
    } finally {
      if (cancelBtn.value) {
        proxy.$loading.hide(cancelBtn.value)
      }
    }
  }, 1000)
}
</script>

<style scoped>
/* 样式调整 */
pre {
  background-color: #f4f4f4;
  padding: 10px;
  border-radius: 5px;
  max-height: 300px;
  overflow-y: auto;
}
</style>